/**
 * Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership. Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package com.baijia.commons.validation;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baijia.commons.authentication.BaseResponse;
import com.baijia.commons.constant.Constant;
import com.baijia.commons.util.PPCommonUtils;
/**
 * @title PassportTicketValidator
 * @desc 校验ST逻辑 
 * @author caoliang
 * @date 2015年12月1日
 * @version 1.0
 */
public class PassportTicketValidator implements TicketValidator {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String passportServerValidSTUrlPrefix;

    private String encoding = "UTF-8";
    
    private String appId;
    
    public PassportTicketValidator(String passportServerUrlPrefix, String appId){
        this.passportServerValidSTUrlPrefix = passportServerUrlPrefix;
        this.appId = appId;
    }
    
    @Override
    public BaseResponse validate(final String ticket, final String service) throws TicketValidationException {

        final String validationUrl = constructValidationUrl(ticket, service);
        if (logger.isDebugEnabled()) {
            logger.debug("Constructing validation url: " + validationUrl);
        }

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Retrieving response from server.");
            }
            final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket);

            if (serverResponse == null) {
                throw new TicketValidationException(
                    "The Passport server returned no response.validationUrl" + validationUrl + "pp_ticket:" + ticket);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Server response: " + serverResponse);
            }

            return parseResponseFromServer(serverResponse);
        } catch (final MalformedURLException e) {
            logger.error("|Passport error|validate pp_ticket|", e);
            throw new TicketValidationException(e);
        }
    }

    protected final String retrieveResponseFromServer(final URL validationUrl, final String ticket) {
        return PPCommonUtils.getResponseFromServer(validationUrl, getEncoding());
    }

    protected final BaseResponse parseResponseFromServer(final String response) throws TicketValidationException {

        BaseResponse baseResponse = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            baseResponse = mapper.readValue(response, BaseResponse.class);
        } catch (IOException e) {
            logger.error("|Passport error!|parseResponseFromServer", e);
        }
        return baseResponse;
    }

    protected final String constructValidationUrl(final String ticket, final String serviceUrl) {
        final Map<String, String> urlParameters = new HashMap<String, String>();

        if (logger.isDebugEnabled()) {
            logger.debug("Placing URL parameters in map.ticket:{},serviceUrl:{}", ticket, serviceUrl);
        }
        urlParameters.put(Constant.ARTIFACTPARAMETERNAME, ticket);
        urlParameters.put(Constant.SERVICEPARAMETERNAME, encodeUrl(serviceUrl));
        urlParameters.put(Constant.APPID, appId );

        final StringBuilder buffer =
            new StringBuilder(urlParameters.size() * 10 + this.passportServerValidSTUrlPrefix.length() + 1);

        int i = 0;

        buffer.append(this.passportServerValidSTUrlPrefix);

        for (Map.Entry<String, String> entry : urlParameters.entrySet()) {
            final String key = entry.getKey();
            final String value = entry.getValue();

            if (value != null) {
                buffer.append(i++ == 0 ? "?" : "&");
                buffer.append(key);
                buffer.append("=");
                buffer.append(value);
            }
        }

        return buffer.toString();

    }

    protected final String encodeUrl(final String url) {
        if (url == null) {
            return null;
        }

        try {
            return URLEncoder.encode(url, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            return url;
        }
    }

    public String getPassportServerUrlPrefix() {

        return passportServerValidSTUrlPrefix;
    }

    public void setPassportServerUrlPrefix(String passportServerUrlPrefix) {

        this.passportServerValidSTUrlPrefix = passportServerUrlPrefix;
    }

    public String getEncoding() {

        return encoding;
    }

    public void setEncoding(String encoding) {

        this.encoding = encoding;
    }

}
